import { CustRequest } from "../../api/cust_request";
import { TencentCosApi } from "../../api/tencent_cos_api";

export const custUploadImg = function(that, type, maxCount, callback = (res)=>{}, addWatermark = 0){
  uni.chooseImage({
    count: maxCount, // 最多可以选择的图片张数，默认为9
    sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
    sourceType: type, // album 从相册选图，camera 使用相机，默认二者都有
    success: (res) => {
      // 选择图片成功的回调函数
      
      console.log(res.tempFilePaths); // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      console.log(res.tempFiles); // 返回选定照片的信息列表，每一项是一个 File 对象

      let resultAry = []
      for(var i=0;i<res.tempFilePaths.length;i++){
        let tempFilePath = res.tempFilePaths[i]
        let genFileName = getUuiD(32) + tempFilePath.substring(tempFilePath.lastIndexOf("."))
        uni.showLoading({
          title: '上传中',
          mask: true
        })
        uni.uploadFile({
          url: TencentCosApi.uploadImageUrl,
             header: {
            'userId': that.$store.state.sessionDto.userDto.userId
          },
          filePath: tempFilePath,
          name: 'file',
          formData: {
            // 'fileName': 'aaa' + tempFilePath.substring(tempFilePath.lastIndexOf('.'))
            'fileName': genFileName,
            'addWatermark': addWatermark
          },
          success: (res) => {
            console.log('图片上传返回结果', res)
            let custRes = JSON.parse(res.data)
            uni.hideLoading()
            console.log('上传返回结果的数组', resultAry)
            callback(custRes,)
            // if (res.code == 200) {
            //   resultAry.push(res.data)
            // }
          },
          fail: (err) => {
            console.error('上传失败', err);
          },
        })
      }
      
    },
    fail: (err) => {
      // 用户取消选择或选择失败的回调函数
      console.error(err.errMsg);
    },
    complete: () => {
      // 接口调用结束的回调函数（调用成功、失败都会执行）
    }
  });
}

function getUuiD(randomLength) {
  return Number(Math.random().toString().substr(2, randomLength) + Date.now()).toString(36)
}

export const custUploadFromAlbumAndCamera = function(that, maxCount, callback = (res)=>{}){
  return uploadImg(that, ['album', 'camera'], maxCount, callback)
}

export const custUploadFromAlbum = function(that, maxCount, callback = (res)=>{}){
  return uploadImg(that, ['album'], maxCount, callback)
}

export const custUploadFromCamera = function(that, maxCount, callback = (res)=>{}){
  return uploadImg(that, ['camera'], maxCount, callback)
}

export const customUploadVideo = function(that, callback = (res) => {}){
  uni.chooseVideo({
    count: 1,
    sourceType: ['camera','album'],
    success: res => {
      console.log('开始录制视频返回', res.tempFilePath)
      // this.videoPath = res.tempFilePath;
      let genFileName = getUuiD(32) + res.tempFilePath.substring(res.tempFilePath.lastIndexOf("."))
      uni.uploadFile({
        url: TencentCosApi.uploadImageUrl,
           header: {
          'userId': CustRequest.defaultUserId
        },
        filePath: res.tempFilePath,
        name: 'file',
        formData: {
          // 'fileName': 'aaa' + tempFilePath.substring(tempFilePath.lastIndexOf('.'))
          'fileName': genFileName,
        },
        success: (res) => {
          console.log('图片上传返回结果', res)
          let custRes = JSON.parse(res.data)
          callback(custRes)
          // if (res.code == 200) {
          //   resultAry.push(res.data)
          // }
        },
        fail: (err) => {
          console.error('上传失败', err);
        },
      })
      // callback({
      //   code: 200,
      //   data: res.tempFilePath
      // })
      // getTempFilePath(res.tempFilePath, 'videoTempPath');
    },
    fail: (err) => {
      console.log('用户未录制视频', err)
      uni.getSetting({
        success: (res) => {
          let authStatus = res.authSetting['scope.camera'];
          if (!authStatus) {
            // uni.showModal({
            //   title: '授权失败',
            //   content: 'Hello uni-app需要从您的相机获取视频，请在设置界面打开相关权限',
            //   success: (res) => {
            //     if (res.confirm) {
            //       uni.openSetting()
            //     }
            //   }
            // })
          }
        }
      })
    }
  });
}
const getTempFilePath = function(url, types) {
  uni.showLoading({
    title: '保存中...'
  });
  // 如果已经下载本地路径，那么直接储存
  let obj = {
    filePath: url,
    success: () => {
      uni.showModal({
        content: '保存成功',
        showCancel: false
      });
      uni.hideLoading();
    },
    fail: e => {
      uni.hideLoading();
      uni.showModal({
        content: '保存失败',
        showCancel: false
      });
    }
  };
  
  if (types === 'videoTempPath') {
    uni.saveVideoToPhotosAlbum(obj);
  } else {
    uni.saveImageToPhotosAlbum(obj);
  }
}
